package consume.listener;

import com.alibaba.fastjson2.util.DateUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Argument;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Kevin
 * @date 2023/6/11 12:46
 * @description 监听延时消息消息
 **/
@Slf4j
@Component
public class TtlListener {

  /**
   * 延时1000ms的队列
   * 绑定死信队列dead-exchange
   * x-message-ttl: 消息过期时间
   * x-dead-letter-exchange: 死信交换机
   * x-dead-letter-routing-key: 死信交换机路由key
   *
   * 延迟队列原理： 消息在指定时间过期后会进入死信队列
   * 过期条件：
   * 1. 消息超过了自己设置的过期时间没有被消费
   * 2. 消息超过了消息队列设置的过期时间没有被消费
   *
   * @param msg
   */
  @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "ttl1",
          arguments = {@Argument(name = "x-message-ttl", value = "10000", type = "java.lang.Integer"),
          @Argument(name = "x-dead-letter-exchange",value = "dead-exchange"),
          @Argument(name = "x-dead-letter-routing-key",value = "dead",type = "java.lang.Object")}),
          exchange = @Exchange(value = "ttl-exchange", type = "direct"),
          key = {"ttl1"}))
  public void listener1(String msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                        Channel channel) throws Exception{
    log.info("{}ttl1监听到延时消息--{}", DateUtils.format(new Date(),"yyyy-dd-MM HH:mm:ss"),msg);

    // 不签收（过期后进入死信队列）
    channel.abort();
//    channel.basicAck(deliveryTag, true);

  }


}
